package com.chenwenxuan.sync.console.dao;

import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.springframework.jdbc.core.BatchPreparedStatementSetter;

import com.chenwenxuan.sync.console.model.TaskDebugInfo;
import com.chenwenxuan.sync.console.model.TaskRuntimeInfo;

public class TaskRuntimeInfoDao extends AbstractDao  {
	
	public void addRuntimeInfoEntry(TaskRuntimeInfo runtimeInfo) {
		getJdbcTemplate().update(addRuntimeInfoEntrySql, 
			new Object[]{runtimeInfo.getRefTask().getTaskId(), runtimeInfo.getRefTask().getTaskId(),
				runtimeInfo.getMsg(), runtimeInfo.getResultCode(), runtimeInfo.getWorkCount()}
		);
	}
	
	public void addDebugLogs(TaskRuntimeInfo runtimeInfo) {
		
		final TaskDebugInfo[] debugInfo = runtimeInfo.getDebugLogs();
		final TaskRuntimeInfo myInfo = runtimeInfo;
		
		getJdbcTemplate().batchUpdate(addDebugLogsSql, new BatchPreparedStatementSetter() {
			
			@Override
			public void setValues(PreparedStatement ps, int i) throws SQLException {
				int k = 0;
				TaskDebugInfo ti = debugInfo[i];
				ps.setInt(k++, myInfo.getRefTask().getTaskId());
				ps.setString(k++, myInfo.getRefTask().getLastExecute());
				ps.setInt(k++, i);
				ps.setString(k++, ti.getMsg());
				ps.setString(k++, ti.getTime());
			}
			
			@Override
			public int getBatchSize() {
				return debugInfo.length;
			}
		});
		
	}
	
	private String addRuntimeInfoEntrySql = 
			"insert into TASK_RUN_HIS (TASK_ID,EXECUTE_TIME,MSG,RESULT_CODE,WORK_COUNT) "
			+ "values (?,?,?,?,?) ";
	private String addDebugLogsSql = "insert into TASK_DEBUG_LOG (TASK_ID,LAST_EXECUTE ,\"ORDER\" , MESSAGE , EXECUTE_TIME) "
			+ "values (?,?,?,?,?,?)";
	


}
